
// 存储当前分享配置
let currentShareConfig = null;

/**
 * 从URL中获取指定参数（支持哈希路由）
 * @param {string} name 参数名
 * @param {string} url URL字符串，默认为当前页面URL
 * @returns {string|null} 参数值
 */
function getQueryParam(name, url = window.location.href) {
  // 处理哈希路由的情况
  const hashIndex = url.indexOf('#');
  let queryString = '';
  
  if (hashIndex > -1) {
    // 获取#后面的部分
    const hashPath = url.substr(hashIndex + 1);
    // 获取?后面的查询参数
    const queryIndex = hashPath.indexOf('?');
    if (queryIndex > -1) {
      queryString = hashPath.substr(queryIndex + 1);
    }
  } else {
    // 普通URL处理
    const queryIndex = url.indexOf('?');
    if (queryIndex > -1) {
      queryString = url.substr(queryIndex + 1);
    }
  }
  
  const params = new URLSearchParams(queryString);
  return params.get(name);
}

/**
 * 获取默认分享配置
 * @returns {Promise<Object>} 分享配置对象
 */
export async function getDefaultShareConfig() {
    // 从当前URL获取meeting_id参数
    return {
      title: '吏简',
      desc:  '智能合同服务平台',
      imgUrl:'https://www.stellargang.cn/h5/static/logo.png',
      link: "https://www.stellargang.cn/h5"  // 分享链接去掉哈希部分
    };
}

/**
 * 设置当前页面的分享配置
 * @param {Object} config 分享配置 {title, desc, imgUrl, link}
 */
export function setPageShareConfig(config) {
  currentShareConfig = config;
  initWxShare();
}

/**
 * 获取当前有效的分享配置
 * @returns {Object} 分享配置
 */
export function getCurrentShareConfig() {
  return currentShareConfig;
}

/**
 * 初始化微信分享
 * @param {Object} config 可选，如果不传则使用currentShareConfig
 */
export function initWxShare(config) {
  // 如果传入了配置，更新currentShareConfig
  if (config) {
    currentShareConfig = config;
  }
  const shareConfig = currentShareConfig;
  if (!shareConfig) return false;
  
  // 确保jWeixin对象已加载
  if (typeof jWeixin === 'undefined' || typeof jWeixin.config !== 'function') {
    console.error('微信JS-SDK未正确加载');
    return false;
  }
  
  // 优化处理：直接尝试设置分享，同时添加ready事件监听作为后备
  try {
    // 立即尝试应用分享配置
    applyShareConfig(shareConfig);
  } catch (immediateError) {
    console.warn('立即应用分享配置失败，将在SDK就绪后重试', immediateError);
  }
  
  // 使用闭包和标志变量来避免重复调用
  let callbackCalled = false;
  const readyCallback = function() {
    if (!callbackCalled) {
      callbackCalled = true;
      try {
        applyShareConfig(shareConfig);
      } catch (readyError) {
        console.error('SDK就绪后应用分享配置失败', readyError);
      }
    }
  };
  
  // 无论当前状态如何，都添加ready事件监听作为保障
  jWeixin.ready(readyCallback);
  
  return true;
}

/**
 * 应用分享配置到微信SDK
 * @param {Object} shareConfig 分享配置对象
 */
function applyShareConfig(shareConfig) {
  try {    
    // 检查API是否可用
    jWeixin.checkJsApi({
      jsApiList: ['updateAppMessageShareData', 'updateTimelineShareData', 'onMenuShareAppMessage', 'onMenuShareTimeline'],
      success: function(res) {        
        // 优先使用新接口，如果失败则回退到旧接口
        // 设置分享给朋友
        try {
          if (res.checkResult.updateAppMessageShareData) {
            jWeixin.updateAppMessageShareData({
              title: shareConfig.title,
              desc: shareConfig.desc,
              link: shareConfig.link,
              imgUrl: shareConfig.imgUrl,
              success: function() {
              },
              fail: function(err) {
                // 回退到旧接口
                if (typeof jWeixin.onMenuShareAppMessage === 'function') {
                  jWeixin.onMenuShareAppMessage({
                    title: shareConfig.title,
                    desc: shareConfig.desc,
                    link: shareConfig.link,
                    imgUrl: shareConfig.imgUrl,
                    success: function() {
                      console.log('旧接口-分享朋友设置成功', shareConfig);
                    }
                  });
                }
              }
            });
          } else if (typeof jWeixin.onMenuShareAppMessage === 'function') {
            // 直接使用旧接口
            jWeixin.onMenuShareAppMessage({
              title: shareConfig.title,
              desc: shareConfig.desc,
              link: shareConfig.link,
              imgUrl: shareConfig.imgUrl,
              success: function() {
                console.log('旧接口-分享朋友设置成功', shareConfig);
              }
            });
          }
        } catch (e) {
          console.error('设置分享朋友配置时发生错误:', e);
        }
        
        // 设置分享到朋友圈
        try {
          if (res.checkResult.updateTimelineShareData) {
            jWeixin.updateTimelineShareData({
              title: shareConfig.title,
              link: shareConfig.link,
              imgUrl: shareConfig.imgUrl,
              success: function() {
              },
              fail: function(err) {
                // 回退到旧接口
                if (typeof jWeixin.onMenuShareTimeline === 'function') {
                  jWeixin.onMenuShareTimeline({
                    title: shareConfig.title,
                    link: shareConfig.link,
                    imgUrl: shareConfig.imgUrl,
                    success: function() {
                      console.log('旧接口-分享朋友圈设置成功', shareConfig);
                    }
                  });
                }
              }
            });
          } else if (typeof jWeixin.onMenuShareTimeline === 'function') {
            // 直接使用旧接口
            jWeixin.onMenuShareTimeline({
              title: shareConfig.title,
              link: shareConfig.link,
              imgUrl: shareConfig.imgUrl,
              success: function() {
                console.log('旧接口-分享朋友圈设置成功', shareConfig);
              }
            });
          }
        } catch (e) {
          console.error('设置分享朋友圈配置时发生错误:', e);
        }
      },
      fail: function(err) {
        console.error('检查JSAPI可用性失败:', err);
        // 即使检查失败，也尝试直接设置分享
        try {
          // 同时尝试新接口和旧接口
          if (typeof jWeixin.updateAppMessageShareData === 'function') {
            jWeixin.updateAppMessageShareData({
              title: shareConfig.title,
              desc: shareConfig.desc,
              link: shareConfig.link,
              imgUrl: shareConfig.imgUrl
            });
          }
          if (typeof jWeixin.onMenuShareAppMessage === 'function') {
            jWeixin.onMenuShareAppMessage({
              title: shareConfig.title,
              desc: shareConfig.desc,
              link: shareConfig.link,
              imgUrl: shareConfig.imgUrl
            });
          }
          if (typeof jWeixin.updateTimelineShareData === 'function') {
            jWeixin.updateTimelineShareData({
              title: shareConfig.title,
              link: shareConfig.link,
              imgUrl: shareConfig.imgUrl
            });
          }
          if (typeof jWeixin.onMenuShareTimeline === 'function') {
            jWeixin.onMenuShareTimeline({
              title: shareConfig.title,
              link: shareConfig.link,
              imgUrl: shareConfig.imgUrl
            });
          }
        } catch (e) {
          console.error('尝试设置分享配置时发生错误:', e);
        }
      }
    });
  } catch (error) {
    console.error('应用分享配置时出错', error);
  }
}
